<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue号码格式化</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <input type="text" v-model="phoneNum">
</div>
</body>
<script>
    let vm = new Vue({
        el: '#app',
        data() {
            return {
                phoneNum: ''
            }
        },
        watch: {
            phoneNum(newVal, oldVal) {
                //  输入过程中
                if (newVal > oldVal) {
                    if (newVal.length === 4 || newVal.length === 9) {
                        let pre = newVal.substring(0, newVal.length - 1)
                        let end = newVal.substr(newVal.length - 1,1)
                        this.phoneNum = pre + ' ' + end
                    } else {
                        this.phoneNum = newVal
                    }
                } else {
                    // 退格过程中     123 3333 4444
                    if (newVal.length === 9 || newVal.length === 4) {
                        this.phoneNum = this.phoneNum.trim()
                    } else {
                        this.phoneNum = newVal
                    }
                }
            }
        }
    })
</script>
</html>
